#include "savecurvedialog.h"
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFileDialog>

#include <QDebug>

SaveCurveDialog::SaveCurveDialog(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(tr("SaveCurveDialog"));
    setAttribute(Qt::WA_DeleteOnClose, true);

    // 初始化控件
    QLabel *lb = new QLabel();
    lb->setText(tr("File Name"));
    m_leFileName = new QLineEdit();
    connect(m_leFileName, &QLineEdit::textChanged, this, [=](const QString &text){
        emit changeConfig(m_lePeriod->text().toInt(), m_leFileName->text());
    });
    m_pbFileName = new QPushButton();
    m_pbFileName->setText("...");
    QHBoxLayout *hblFileName = new QHBoxLayout();
    hblFileName->addWidget(lb);
    hblFileName->addWidget(m_leFileName);
    hblFileName->addWidget(m_pbFileName);
    connect(m_pbFileName, &QPushButton::clicked, this, [=](){
        QString path;
        QString fileName = m_leFileName->text();
        if (fileName.isEmpty())
        {
            path = ".";
        }
        else
        {
            QFileInfo info = QFileInfo(fileName);
            path = info.path();
        }
        fileName = QFileDialog::getSaveFileName(this, "save as file", ".");
        m_leFileName->setText(fileName);
    });

    lb = new QLabel();
    lb->setText(tr("Period(ms)"));
    m_lePeriod = new QLineEdit();
    connect(m_lePeriod, &QLineEdit::textChanged, this, [=](const QString &text){
        emit changeConfig(m_lePeriod->text().toInt(), m_leFileName->text());
    });
    QHBoxLayout *hblPeriod = new QHBoxLayout();
    hblPeriod = new QHBoxLayout();
    hblPeriod->addWidget(lb);
    hblPeriod->addWidget(m_lePeriod);

    m_pbStatus = new QPushButton();
    m_pbStatus->setText(tr("Start"));
    connect(m_pbStatus, &QPushButton::clicked, this, [=](){
        if (!m_isStartd)
        {
            QFileInfo info = QFileInfo(m_leFileName->text());
            if (info.dir().exists()) // 文件夹路径是否存在
            {
                emit changeStatus(true);
            }
        }
        else
        {
            emit changeStatus(false);
        }
        close();
    });
    QPushButton *pbQuit = new QPushButton();
    pbQuit->setText(tr("Quit"));
    connect(pbQuit, &QPushButton::clicked, this, &SaveCurveDialog::close);
    QHBoxLayout *hblButton = new QHBoxLayout();
    hblButton->addWidget(m_pbStatus);
    hblButton->addWidget(pbQuit);

    QVBoxLayout *vbl = new QVBoxLayout();
    vbl->addLayout(hblFileName);
    vbl->addLayout(hblPeriod);
    vbl->addLayout(hblButton);
    setLayout(vbl);
}

void SaveCurveDialog::setConfig(int period, const QString &fileName)
{
    m_lePeriod->setText(QString::number(period));
    m_leFileName->setText(fileName);
}

void SaveCurveDialog::setStatus(bool isStart)
{
    m_isStartd = isStart;
    m_pbFileName->setEnabled(!isStart);
    m_leFileName->setEnabled(!isStart);
    m_lePeriod->setEnabled(!isStart);
    m_pbStatus->setText(isStart ? tr("Stop") : tr("Start"));
}
